﻿import 'package:azring/core/models/health_plan.dart';
import 'package:azring/pages/action/questionnaire/routes.dart';
import 'package:azring/pages/status/routes.dart';
import 'package:azring/pages/status/status_logic.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'actionLogic.dart';
import '../../core/models/action_record.dart';
import '../../common/styles/theme_manager.dart';
import '../../gen/assets.gen.dart';

/// 行动页面
class ActionView extends GetView<ActionLogic> {
  const ActionView({super.key});

  Widget _buildView() {
    return Container(
      color: Colors.black,
      child: SafeArea(
        child: SingleChildScrollView(
          child: Stack(
            children: [
              // 顶部渐变背景
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                height: 240.h,
                child: Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topRight,
                      end: Alignment.bottomRight,
                      colors: ThemeManager.to.backgroundGradientColors,
                      stops: const [0.1, 0.3, 0.7, 1.0],
                    ),
                  ),
                ),
              ),
              // 主要内容
              Padding(
                padding: EdgeInsets.all(16.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildGreeting(),
                    SizedBox(height: 24.h),
                    _buildQuickActions(),
                    SizedBox(height: 32.h),
                    _buildSectionTitle('正念冥想'),
                    SizedBox(height: 16.h),
                    _buildActionGrid(),
                    SizedBox(height: 32.h),
                    _buildSectionTitle('健康计划'),
                    SizedBox(height: 16.h),
                    _buildHealthPlanSection(),
                    SizedBox(height: 32.h), // 底部额外间距
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildGreeting() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '行动',
          style: TextStyle(
            fontSize: 28.sp,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        SizedBox(height: 8.h),
        Text(
          _getGreetingText(),
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.white70,
          ),
        ),
      ],
    );
  }

  String _getGreetingText() {
    return '缓解一下';
  }

  Widget _buildQuickActions() {
    return Row(
      children: [
        Expanded(
          child: _buildQuickActionCard(
            title: '减压',
            subtitle: '4-4',
            icon: Icons.track_changes,
            color: const Color(0xFFFF7043),
            onTap: () => controller.openGoalTracking(),
            backgroundImage: Assets.action.decompressionColorBg.path,
            cornerImage: Assets.action.decompression.path,
          ),
        ),
        SizedBox(width: 16.w),
        Expanded(
          child: _buildQuickActionCard(
            title: '助眠',
            subtitle: '4-7-8',
            icon: Icons.repeat,
            color: const Color(0xFF4FC3F7),
            onTap: () => controller.openHabitBuilding(),
            backgroundImage: Assets.action.sleepyColorBg.path,
            cornerImage: Assets.action.sleepyBg.path,
          ),
        ),
      ],
    );
  }

  Widget _buildQuickActionCard({
    required String title,
    required String subtitle,
    required IconData icon,
    required Color color,
    required VoidCallback onTap,
    String? backgroundImage,
    String? cornerImage,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 90.h,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.r),
          gradient: backgroundImage != null
              ? LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    Colors.black.withOpacity(0.4),
                    Colors.black.withOpacity(0.2),
                  ],
                )
              : null,
          color: backgroundImage == null ? Colors.black.withOpacity(0.3) : null,
          border: Border.all(color: Colors.white.withOpacity(0.1)),
        ),
        child: Stack(
          children: [
            // 背景图片
            if (backgroundImage != null)
              Positioned.fill(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(12.r),
                  child: Image.asset(
                    backgroundImage,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        decoration: BoxDecoration(
                          color: Colors.black.withOpacity(0.3),
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                      );
                    },
                  ),
                ),
              ),
            // 右下角背景图片
            if (cornerImage != null)
              Positioned(
                bottom: 0,
                right: 0,
                child: Container(
                  width: 60.w,
                  height: 60.h,
                  child: Image.asset(
                    cornerImage,
                    fit: BoxFit.contain,
                    errorBuilder: (context, error, stackTrace) {
                      return SizedBox.shrink();
                    },
                  ),
                ),
              ),
            // 内容
            Padding(
              padding: EdgeInsets.all(16.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.white,
                    ),
                  ),
                  Spacer(),
                  // Row(
                  //   children: [
                  //     Icon(
                  //       Icons.arrow_forward_ios,
                  //       color: Colors.white,
                  //       size: 16.sp,
                  //     ),
                  //   ],
                  // ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Text(
      title,
      style: TextStyle(
        fontSize: 17.sp,
        fontWeight: FontWeight.w500,
        color: const Color(0xffF9F8F7),
      ),
    );
  }

  Widget _buildActionGrid() {
    return Obx(() {
      if (controller.state.actionTypes.isEmpty) {
        return SizedBox(
          height: 115.h,
          child: Center(
            child: Text(
              '暂无行动类型',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.white70,
              ),
            ),
          ),
        );
      }

      return SizedBox(
        height: 115.h,
        child: ListView.separated(
          padding: EdgeInsets.symmetric(horizontal: 4.w),
          physics: const BouncingScrollPhysics(),
          scrollDirection: Axis.horizontal,
          itemCount: controller.state.actionTypes.length,
          separatorBuilder: (_, __) => SizedBox(width: 16.w),
          itemBuilder: (context, index) {
            final actionType = controller.state.actionTypes[index];
            return _buildActionTypeCard(actionType, index);
          },
        ),
      );
    });
  }

  Widget _buildActionTypeCard(Map<String, dynamic> actionType, int index) {
    // 从字典数据中获取信息
    final String label = actionType['dictLabel'] ?? '未命名';
    final String value = actionType['dictValue'] ?? '';
    final String? imageName = actionType['remark']; // remark 字段存储图片名称

    return GestureDetector(
      onTap: () => controller.openActionCategory(value, label),
      child: Container(
        width: 100.w,
        height: 115.h,
        decoration: BoxDecoration(
          color: const Color(0xFF282528),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 图标图片
            _getImageFromName(imageName, value),
            SizedBox(height: 28.h),
            // 课程名称
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 8.w),
              child: Text(
                label,
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
                textAlign: TextAlign.center,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 根据图片名称或 dictValue 获取对应的图片
  Widget _getImageFromName(String? imageName, String dictValue) {
    // 图片映射表：根据 remark 或 dictValue 映射到对应的图片
    final Map<String, Widget> imageMap = {
      // 根据 remark 字段映射
      'task_think': Assets.action.taskThink.image(width: 40.w, height: 40.h),
      'task_emotion':
          Assets.action.taskEmotion.image(width: 40.w, height: 40.h),
      'task_treatment':
          Assets.action.taskTreatment.image(width: 40.w, height: 40.h),
      'task_option': Assets.action.taskOption.image(width: 40.w, height: 40.h),

      // 根据 dictValue 映射（备用方案）
      '1': Assets.action.taskThink.image(width: 40.w, height: 40.h), // 正念冥想
      '2': Assets.action.taskEmotion.image(width: 40.w, height: 40.h), // 情绪管理
      '3': Assets.action.taskTreatment.image(width: 40.w, height: 40.h), // 疗愈
      '4': Assets.action.taskOption.image(width: 40.w, height: 40.h), // 场景
    };

    // 优先使用 remark 字段，如果没有则使用 dictValue
    if (imageName != null &&
        imageName.isNotEmpty &&
        imageMap.containsKey(imageName)) {
      return imageMap[imageName]!;
    } else if (imageMap.containsKey(dictValue)) {
      return imageMap[dictValue]!;
    }

    // 默认图片
    return Assets.action.taskThink.image(width: 40.w, height: 40.h);
  }

  Widget _buildHealthPlanSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(height: 12.h),
        Obx(() => Row(
              children: [
                _buildFilterChip('进行中',
                    isActive: controller.state.planFilter.value == '进行中',
                    onTap: () => controller.state.planFilter.value = '进行中'),
                SizedBox(width: 12.w),
                _buildFilterChip('已生成',
                    isActive: controller.state.planFilter.value == '已生成',
                    onTap: () => controller.state.planFilter.value = '已生成'),
                SizedBox(width: 12.w),
                _buildFilterChip('已完成',
                    isActive: controller.state.planFilter.value == '已完成',
                    onTap: () => controller.state.planFilter.value = '已完成'),
                Spacer(),
                GestureDetector(
                  onTap: () => _showPlanOptionsDialog(),
                  child: Container(
                    width: 32.w,
                    height: 32.w,
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.3),
                      shape: BoxShape.circle,
                      border: Border.all(color: Colors.white.withOpacity(0.1)),
                    ),
                    child: Icon(Icons.add, color: Colors.white70, size: 18.sp),
                  ),
                ),
              ],
            )),
        SizedBox(height: 16.h),
        Obx(() => Row(
          children: [
            Text(
              '由问卷生成计划',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.white38,
              ),
            ),
            const Spacer(),
            if (controller.state.planFilter.value == '进行中')
              Text(
                '默认循环执行',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.white38,
                ),
              ),
          ],
        )),
        SizedBox(height: 12.h),
        _buildHealthPlansList(),
      ],
    );
  }

  Widget _buildFilterChip(String label,
      {bool isActive = false, VoidCallback? onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
        decoration: BoxDecoration(
          color: isActive
              ? const Color(0xFFDB885F).withOpacity(0.2)
              : Colors.black.withOpacity(0.3),
          borderRadius: BorderRadius.circular(8.r),
          border: Border.all(
              color: isActive
                  ? const Color(0xFFDB885F)
                  : Colors.white.withOpacity(0.1)),
        ),
        child: Text(
          label,
          style: TextStyle(
            fontSize: 14.sp,
            color: isActive ? const Color(0xFFDB885F) : Colors.white70,
          ),
        ),
      ),
    );
  }

  Widget _buildHealthPlansList() {
    return Obx(() {
      if (controller.state.isLoadingHealthPlans.value) {
        return Container(
          width: double.infinity,
          height: 104.h,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16.r),
            color: const Color(0xff282528),
          ),
          child: Center(
            child: CircularProgressIndicator(
              color: Colors.white,
              strokeWidth: 2.0,
            ),
          ),
        );
      }

      final filteredPlans = controller.state.filteredHealthPlans;

      if (filteredPlans.isEmpty) {
        return Container(
          width: double.infinity,
          height: 104.h,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16.r),
            color: const Color(0xff282528),
          ),
          child: Center(
            child: Text(
              '暂无${controller.state.planFilter.value}计划',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.white70,
              ),
            ),
          ),
        );
      }

      // 如果只有一个计划，显示单个卡片
      if (filteredPlans.length == 1) {
        return _buildSingleHealthPlanCard(filteredPlans.first);
      }

      // 如果有多个计划，显示列表
      return Column(
        children: filteredPlans
            .map((plan) => Padding(
                  padding: EdgeInsets.only(bottom: 12.h),
                  child: _buildSingleHealthPlanCard(plan),
                ))
            .toList(),
      );
    });
  }

  Widget _buildSingleHealthPlanCard(HealthPlan plan) {
    return GestureDetector(
      onTap: () {
        // 点击卡片跳转到计划详情页（查看模式）
        Get.toNamed('/action/create-plan', arguments: {
          'planId': plan.id?.toString(),
          'isViewMode': true,
        });
      },
      child: Container(
        width: double.infinity,
        height: 104.h,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16.r),
            color: const Color(0xff282528)),
        child: Stack(
        children: [
          // 背景图片
          Positioned(
            top: 0,
            right: 0,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(16.r),
              child: Assets.action.planBg.image(
                width: 104.w,
                height: 104.h,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    width: 104.w,
                    height: 104.h,
                    decoration: BoxDecoration(
                      color: const Color(0xff282528),
                      borderRadius: BorderRadius.circular(16.r),
                    ),
                  );
                },
              ),
            ),
          ),
          // 内容层
          Positioned(
            bottom: -15,
            left: 0,
            right: 0,
            child: Padding(
              padding: EdgeInsets.fromLTRB(16.w, 0, 16.w, 16.h),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 计划名称
                  Text(
                    plan.planName ?? '未命名计划',
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.white,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 8.h),
                  // 顶部状态和进度信息
                  Row(
                    children: [
                      // 状态标签
                      Container(
                        padding: EdgeInsets.symmetric(
                            horizontal: 8.w, vertical: 4.h),
                        decoration: BoxDecoration(
                          color: _getStatusColor(plan.planStatus),
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                        child: Text(
                          plan.statusText,
                          style: TextStyle(
                            fontSize: 10.sp,
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                      SizedBox(width: 8.w),
                      // 进度文本
                      Text(
                        '${plan.planProgress ?? 0}',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.white,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      Text(
                        '/${plan.planCycle ?? 0}天',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.white70,
                        ),
                      ),
                      Spacer(),
                      // 积分显示或领取按钮
                      if (plan.canClaimPoints)
                        GestureDetector(
                          onTap: () => controller.claimPoints(plan),
                          child: Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: 8.w, vertical: 4.h),
                            decoration: BoxDecoration(
                              color: const Color(0xFFDB885F),
                              borderRadius: BorderRadius.circular(8.r),
                            ),
                            child: Text(
                              '领取${plan.planPoints ?? 0}积分',
                              style: TextStyle(
                                fontSize: 10.sp,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        )
                      else
                        Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: 8.w, vertical: 4.h),
                          decoration: BoxDecoration(
                            color: Colors.grey.withOpacity(0.2),
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                          child: Text(
                            '${plan.planPoints ?? 0}积分',
                            style: TextStyle(
                              fontSize: 10.sp,
                              color: Colors.white,
                            ),
                          ),
                        ),
                    ],
                  ),
                  SizedBox(height: 12.h),
                  // 进度条
                  Row(
                    children: [
                      Expanded(
                        child: Container(
                          height: 8.h,
                          child: Row(
                            children:
                                List.generate(plan.planCycle ?? 30, (index) {
                              return Expanded(
                                child: Container(
                                  margin: EdgeInsets.only(
                                      right: index < (plan.planCycle ?? 30) - 1
                                          ? 2.w
                                          : 0),
                                  height: 8.h,
                                  decoration: BoxDecoration(
                                    color: index < (plan.planProgress ?? 0)
                                        ? const Color(0xFFDB885F)
                                        : Colors.grey.withOpacity(0.3),
                                    borderRadius: BorderRadius.circular(4.r),
                                  ),
                                ),
                              );
                            }),
                          ),
                        ),
                      ),
                      SizedBox(width: 8.w),
                      // 圆形图标
                      Container(
                        width: 24.w,
                        height: 24.w,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          gradient: RadialGradient(
                            colors: [
                              Colors.grey[300]!,
                              Colors.grey[600]!,
                              Colors.grey[800]!,
                            ],
                            stops: [0.0, 0.6, 1.0],
                          ),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.3),
                              blurRadius: 4,
                              offset: Offset(0, 2),
                            ),
                          ],
                        ),
                        child: Center(
                          child: Container(
                            width: 6.w,
                            height: 6.w,
                            decoration: BoxDecoration(
                              color: Colors.grey[800],
                              shape: BoxShape.circle,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    ),
    );
  }

  Color _getStatusColor(String? status) {
    switch (status) {
      case '1': // 进行中
        return const Color(0xFFDB885F);
      case '2': // 已生成
        return const Color(0xFF4FC3F7);
      case '3': // 已完成
        return const Color(0xFF66BB6A);
      default:
        return Colors.grey;
    }
  }

  void _showPlanOptionsDialog() {
    showDialog(
      context: Get.context!,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: const Color(0xFF2D2D2D),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16.r),
          ),
          content: Container(
            width: double.maxFinite,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _buildPlanOption('自定义生成计划', () => _navigateToCreatePlan()),
                _buildPlanOption('根据报告生成计划', () => _generatePlanFromReport()),
                _buildPlanOption(
                    '根据问卷生成计划', () => _generatePlanFromQuestionnaire()),
                _buildPlanOption('AI对话生成计划', () => _generatePlanFromAI()),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildPlanOption(String title, VoidCallback onTap) {
    return GestureDetector(
      onTap: () {
        Get.back();
        onTap();
      },
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(vertical: 16.h),
        child: Text(
          title,
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.white,
          ),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }

  void _navigateToCreatePlan() {
    Get.toNamed('/action/create-plan');
  }

  void _generatePlanFromReport() {
    Toast.show(
      '根据报告生成计划功能开发中',
    );
  }

  void _generatePlanFromQuestionnaire() {
    Get.toNamed(QuestionnaireRoutes.questionnaire);
  }

  void _generatePlanFromAI() {
    // 切换到洞察页面（InsightsView）
    final statusLogic = Get.find<StatusLogic>();
    statusLogic.changeTabIndex(2); // InsightsView 的索引是 2
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        onRefresh: () async {
          await controller.refreshHealthPlans();
        },
        color: Colors.white,
        backgroundColor: const Color(0xFF2D2D2D),
        child: _buildView(),
      ),
    );
  }
}
